package com.xinfu.newproject.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.xinfu.newproject.R;
import com.xinfu.newproject.activity.LoginActivity;
import com.xinfu.newproject.bean.login.LoginBean;
import com.xinfu.newproject.common.SDActivityManager;
import com.xinfu.newproject.util.SPUtils;
import com.xinfu.newproject.util.StatusBarUtil;
import com.xinfu.newproject.widget.kProgressHUD.KProgressHUD;

import java.util.ArrayList;
import java.util.List;

import static com.xinfu.newproject.contants.Constant.LOGIN;

/**
 * User: Losileeya (847457332@qq.com)
 * Date: 2016-09-11
 * Time: 14:32
 * 类描述：
 *
 * @version :
 */
public class BaseActivity<V extends BaseView> extends AppCompatActivity implements BaseView {
    private KProgressHUD progressDialog;//登录进度条
    private RxPermissions rxPermissions;
    protected String TAG = this.getClass().getSimpleName();
    protected int REQUEST_CODE_ASK_PERMISSION = 0x00099;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setRootViewFitsSystemWindows(this, false);
        //设置状态栏透明
        StatusBarUtil.setTranslucentStatus(this);
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtil.setStatusBarColor(this, 0x55000000);
        }
        SDActivityManager.getInstance().onCreate(this);
        progressDialog = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE);//实例化progressDialog
        progressDialog.setCancellable(false);
        progressDialog.setOnKeyListener(onKeyListener);
        // 申请权限
        rxPermissions = new RxPermissions(this);
        initPermissions();

        if (!isLogin()) {
            if (!getClass().getSimpleName().equals("LoginActivity") && !getClass().getSimpleName().equals("WebPayActivity")) {
                startIntentActivity(LoginActivity.class, null);
            }
        }
    }

    private DialogInterface.OnKeyListener onKeyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                dismissDialog();
            }
            return false;
        }
    };

    public void dismissDialog() {
        if (isFinishing()) {
            return;
        }
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
    /**
     * 权限动态申请
     */
    @SuppressLint("CheckResult")
    private void initPermissions() {
        rxPermissions
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_SETTINGS,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.INTERNET)
                .subscribe(granted -> {
                    if (granted) { // Always true pre-M
                        // I can control the camera now
                    } else {
                        // Oups permission denied
                    }
                });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        SDActivityManager.getInstance().onResume(this);
    }

    @Override
    public void showLoding() {
        if (!progressDialog.isShowing())//如果进度条没有显示
            progressDialog.show();//显示进度条
    }

    @Override
    public void hideLoding() {
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }

    @Override
    public void showErr(String err) {
        Toast.makeText(this, err, Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SDActivityManager.getInstance().onDestroy(this);
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }

    /**
     * 需在setContentView方法之后调用. 设置后,如果不对左侧的事件进行监听,默认的点击事件是结束当前界面.
     * <p>
     * 标题传资源id和字符串皆可.
     * <p>
     * 如果某一侧显示的是图片,则那一侧只能传对应的图片资源id.如果是文字,则资源id和字符串皆可.
     *
     * @param title
     *            标题
     */
    protected void setActivityTitle(Object title) {
        try {
            TextView titleText=findViewById(R.id.head_text);
            titleText.setText((String)title);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置点击左上角的返回事件.默认是finish界面
     */
    protected void registerBack() {
        ImageView llLeft = findViewById(R.id.head_back);
        llLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BaseActivity.this.finish();
            }
        });
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * [沉浸状态栏]
     */
    private void steepStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }
    /**
     * [简化Toast]
     * @param msg
     */
    protected void showToast(String msg){
        Toast.makeText(this,msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * [含有Bundle通过Class打开编辑界面]
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startIntentActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * [携带数据的页面跳转]
     *
     * @param clz
     * @param bundle
     */
    public void startIntentActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void startIntentActivityAnim(Class<?> clz, View view, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        ActivityOptionsCompat optionsCompat =
                ActivityOptionsCompat.makeSceneTransitionAnimation(this, view, "image");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            startActivity(intent, optionsCompat.toBundle());
        } else {
            startActivity(intent);
        }
    }
    /**
     * 显示对话框，提示信息填写不完整，自定义文字
     */
    public void showIncompleteAlertDialog(Context context, String content) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCancelable(true).setTitle("提示：").setMessage(content)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();
    }

    /**
     * 判断是否可以请求数据
     */
    String token, userId, userName;

    private boolean isLogin() {

        LoginBean.ResultBean resultBean;
        String responseIntent = (String) SPUtils.get(this, LOGIN, "0");
        if (!responseIntent.equals("0")) {
            resultBean = new Gson().fromJson(responseIntent, LoginBean.ResultBean.class);
            token = resultBean.getToken();
            userId = resultBean.getUserInfo().getId();
            userName = resultBean.getUserInfo().getUsername();
        } else {
            return false;
        }
        return true;
    }

    /**
     * 请求权限
     *
     * @param permissions 请求的权限
     * @param requestCode 请求权限的请求码
     */
    public void requestPermission(String[] permissions, int requestCode) {
        this.REQUEST_CODE_ASK_PERMISSION = requestCode;
        if (checkPermissions(permissions)) {
            permissionGrant(true, REQUEST_CODE_ASK_PERMISSION);
        } else {
            List<String> needPermissions = getDeniedPermissions(permissions);
            ActivityCompat.requestPermissions(this, needPermissions.toArray(new String[needPermissions.size()]), REQUEST_CODE_ASK_PERMISSION);
        }
    }

    /**
     * 打开相机或者相册
     */
    public void onClickCamera() {
//        //文本
//        ArrayList<String> listContent = new ArrayList<String>();
//        listContent.add("拍照");
//        listContent.add("从相册选择");
//
//        //文本颜色
//        ArrayList<String> listColor = new ArrayList<String>();
//        listColor.add("#848484");
//        listColor.add("#d50201");
//
//        //文本字体大小
//        ArrayList<String> listContentSize = new ArrayList<String>();
//        listContentSize.add("20");
//        listContentSize.add("18");
//
//        Bundle bundle = new Bundle();
//        bundle.putBoolean(ItemDialogFragment.DIALOG_BACK, true);
//        bundle.putBoolean(ItemDialogFragment.DIALOG_CANCELABLE, true);
//        bundle.putBoolean(ItemDialogFragment.DIALOG_CANCELABLE_TOUCH_OUT_SIDE, true);
//        bundle.putStringArrayList(ItemDialogFragment.DIALOG_ITEM_CONTENT, listContent);
//        bundle.putStringArrayList(ItemDialogFragment.DIALOG_ITEM_COLOR, listColor);
//        bundle.putStringArrayList(ItemDialogFragment.DIALOG_ITEM_CONTENT_SIZE, listContentSize);
//        bundle.putString(ItemDialogFragment.DIALOG_CANCEL, "取消");
//        final ItemDialogFragment dialogFragment = ItemDialogFragment.newInstance(ItemDialogFragment.class, bundle);
//        dialogFragment.setOnItemClickDialogListener(new ItemDialogFragment.OnItemClickDialogListener() {
//            @Override
//            public void onItemClick(int position, String content) {
//                if (position == 0) {//拍照
//                    pictureForCamera();
//                } else if (position == 1) {//从相册选择
//                    pictureForVanGogh();
//                }
//                dialogFragment.dismiss();
//            }
//
//            @Override
//            public void onCancel(TextView tvCancel) {
//                dialogFragment.dismiss();
//            }
//        });
//        dialogFragment.show(getSupportFragmentManager(), "");
        pictureForVanGogh();
    }

    //=====================================================核心代码===================================================================================================================
    private void pictureForCamera() {//拍照
        requestPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 0x0001);
    }

    private void pictureForVanGogh() {//从相册选择
        requestPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 0x0002);
    }

    /**
     * 检测所有的权限是否都已授权
     *
     * @param permissions
     * @return
     */
    private boolean checkPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 确认所有的权限是否都已授权
     *
     * @param grantResults
     * @return
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     */
    private List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED || ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                needRequestPermissionList.add(permission);
            }
        }
        return needRequestPermissionList;
    }

    /**
     * 系统请求权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_ASK_PERMISSION) {
            if (verifyPermissions(grantResults)) {
                permissionGrant(true, REQUEST_CODE_ASK_PERMISSION);
            } else {
                permissionGrant(false, REQUEST_CODE_ASK_PERMISSION);
                showTipsDialog();
            }
        }
    }

    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        new AlertDialog.Builder(this)
                .setTitle("提示信息")
                .setMessage("当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行授权。")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        startAppSettings();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();
    }

    /**
     * 获取权限是否成功
     *
     * @param isGranted   true:成功权限成功 false:获取权限失败
     * @param requestCode 权限请求码
     */
    @CallSuper
    public void permissionGrant(boolean isGranted, int requestCode) {
        Log.i(TAG, "获取权限是否成功——>" + "isGranted：" + isGranted + " requestCode：" + requestCode);
    }

    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

}
